package com.door.erp.sevice.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.door.erp.constant.Constants;
import com.door.erp.dao.ColorDao;
import com.door.erp.dao.base.GenericDao;
import com.door.erp.enums.BaseInfoStatus;
import com.door.erp.model.Color;
import com.door.erp.pager.Pager;
import com.door.erp.sevice.ColorService;
import com.door.erp.sevice.base.GenericServiceImpl;
import com.door.erp.sevice.base.ValidResultSet;

@Service(value = "colorService")
public class ColorServiceImp extends GenericServiceImpl<Color, Long> implements ColorService,ValidResultSet<Color>{

	private final Logger log = Logger.getLogger(ColorServiceImp.class);
	
	@Resource(name="colorDao", type=ColorDao.class)
	private ColorDao colorDao;
	
	@Override
	public GenericDao<Color, Long> getDao() {
		return colorDao;
	}

	@Override
	public List<Color> getValidateResultSet(Map<String, Object> param,Pager pager) {
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("status", BaseInfoStatus.NORMAL);
		if(param != null) {
			m.putAll(param);
		}
		return this.getAll(m, pager);
	}

	@Override
	public int getValidateResultSetCount(Map<String, Object> param) {
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("status", BaseInfoStatus.NORMAL);
		if(param != null) {
			m.putAll(param);
		}
		return this.getCount(m);
	}

	@Override
	public List<Color> getValidateResultSet(Map<String, Object> param) {
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("status", BaseInfoStatus.NORMAL);
		if(param != null) {
			m.putAll(param);
		}
		return this.getAll(m);
	}

	@Override
	public String addColorImage(MultipartFile image, File dir) {
		if (dir == null || !dir.exists()) {
			dir.mkdirs();
		}
		if(image == null){
			return null;
		}
		if(!image.getContentType().contains("image")){
			return null;
		}
		
		String oldName = image.getOriginalFilename();
		String imgSuffix = oldName.substring(oldName.lastIndexOf(".") + 1);
		String newName = UUID.randomUUID().toString() +"." +imgSuffix;
		File newFile = new File(dir.getAbsolutePath(), newName);
		log.info("oldName = " + oldName + " newName = " + newName);
		try {
			image.transferTo(newFile);
		} catch (IOException e) {
			log.error("保存Color的上传图片出现异常");
			e.printStackTrace();
			return Constants.ERROR;
		}
		return newName;
	}

}
